package com.guli.mall.ali.oss.service.impl;
/*
 * @Author 罗
 * @date 2020/9/19 - 8:16 上午
 */

import com.alibaba.cloud.spring.boot.context.env.AliCloudProperties;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.guli.common.utils.R;
import com.guli.mall.ali.oss.service.OssService;
import com.guli.mall.serviceBase.globalException.MallException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@RefreshScope
@Slf4j
public class OssServiceImpl implements OssService {

    @Resource
    OSS ossClient;

    @Value("${alibaba.cloud.oss.endpoint}")
    String endpoint;

    @Value("${alibaba.cloud.oss.bucket}")
    String bucket;

    @Resource
    AliCloudProperties aliCloudProperties;

    /*@Value("${alibaba.cloud.oss.userDirPrefix}")
    String userDirPrefix;*/

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");

    @Override
    public R getPolicyOfUploadingFile() {

/*        String accessId = "<yourAccessKeyId>"; // 请填写您的AccessKeyId。
        String accessKey = "<yourAccessKeySecret>"; // 请填写您的AccessKeySecret。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // 请填写您的 endpoint。
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        String callbackUrl = "http://88.88.88.88:8888";
        String bucket = "guli-mall-luo"; // 请填写您的 bucketname 。
        String userDirPrefix = "user-dir-prefix/"; // 用户上传文件时指定的前缀。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);*/

        /**
         * https://guli-mall-luo.oss-cn-beijing.aliyuncs.com/150532.jpg
         * 文件的URL就是 bucket.endpoint/文件名  所以要这样拼接
         * */
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

        // 使用日期来作为用户存储的目录
        String userDirPrefix = SIMPLE_DATE_FORMAT.format(new Date());

        R respMap = R.ok();

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            log.info(format.format(expiration) + "，该policy到期");

            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, userDirPrefix);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);


            //respMap.put("accessid", ossClient.getA);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", userDirPrefix);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("OSSAccessKeyId", aliCloudProperties.getAccessKey());
            // respMap.put("expire", formatISO8601Date(expiration));

            /* 因为网关已经解决的跨域，所以这里就不用了
            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);

            JSONObject ja1 = JSONObject.fromObject(respMap);
            // System.out.println(ja1.toString());

            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");

            response(request, response, ja1.toString());
            */
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            //System.out.println(e.getMessage());
            throw new MallException(e.getMessage());
        } finally {
            //ossClient.shutdown();
        }
        return respMap;
    }

    @Override
    public void deleteFile(String objectUrl) {

        //String objectName = objectUrl.substring(objectUrl.lastIndexOf("/") + 1);

        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucket, objectUrl);


        boolean b = ossClient.doesObjectExist(bucket, objectUrl);

        if (b) {
            log.error(objectUrl + "删除失败");

        } else {
            log.info(objectUrl + "已经删除");

        }

        // 关闭OSSClient。
        //ossClient.shutdown();
    }

    @Override
    public String getOssHost() {
        return "https://" + bucket + "." + endpoint;
    }
}
